package cn.net.xyan.easy.webapp.base.config;

import cn.net.xyan.easy.webapp.base.support.PageableResolver;
import cn.net.xyan.easy.webapp.base.utils.WebModuleFinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor;
import org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.persistence.EntityManagerFactory;
import java.util.List;

/**
 * Created by xiashenpin on 16/1/17.
 */
@EnableWebMvc
@ComponentScan(basePackages = {"cn.net.xyan.easy.webapp.base.controller"})
@Configuration("cn.net.xyan.easy.webapp.base.config.MVCConfig")
public class MVCConfig extends WebMvcConfigurerAdapter {

    @Autowired
    EntityManagerFactory emf;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
        registry.addWebRequestInterceptor(openEntityManagerInViewInterceptor());
    }


    @Bean
    public OpenEntityManagerInViewInterceptor openEntityManagerInViewInterceptor(){
        OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor();
        interceptor.setEntityManagerFactory(emf);
        return interceptor;
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(authenticationPrincipalArgumentResolver());
        argumentResolvers.add(pageableResolver());
    }

    @Bean
    public WebModuleFinder webModuleFinder(){
        return new WebModuleFinder();
    }

    @Bean
    public AuthenticationPrincipalArgumentResolver authenticationPrincipalArgumentResolver(){
        return new AuthenticationPrincipalArgumentResolver();
    }

    public PageableResolver pageableResolver(){
        return new PageableResolver();
    }

}
